package xyz.hujf.base.ThreadWaitAndNotify;

/**
 * @author Hujf
 * @title: WatiTest
 * @date 2021-04-2118:32
 * @description:
 * wait 当一个线程调用共享变量wait方法时，该线程会被阻塞，直到以下几种情况才会返回
 * 1.其他线程调用了共享变量的notify或者notifyall 方法   而且必须要释放这个共享变量的锁  wait(1000)  如果超时也一样的
 * 2.其他线程调用了该线程的interrupt方法 抛异常返回
 *
 */
public class WatiTest {

    private static volatile Object resA = new Object();
    private static volatile Object resB = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resA){
                    System.out.println("A上了锁");
                    synchronized (resB){
                        System.out.println("B上了锁");
                        System.out.println("A被锁着了");

                        try {
                            System.out.println("阻塞当前线程释放 资源A的锁");
                            resA.wait(1000);
                            System.out.println("结束线程A");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    synchronized (resA){
                        System.out.println("线程B获得了A的锁");
                        System.out.println("线程B尝试去获取B的锁");
                        synchronized (resB){
                            System.out.println("threadB get b LOCK");

                            System.out.println("释放线程B中A的锁");
                            resA.wait();
                        }

                    }


                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();

    }
}
